<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\CompanyCity;
use App\Models\Shop;
use Illuminate\Http\Request;

class ShopController extends Controller
{
    public function add() {

    }

    public function update() {

    }

    public function import(Request $request) {
        $shops = $request->input('shops');

        foreach ($shops as $key => $shop) {
            $cityName = $shop['city'];
            // 检查城市是否存在
            $city = CompanyCity::where('company', $shop['company'])->where('city_name', $cityName)->first();
            if (!$city) {    // 添加城市
                return self::fail(201, '请先添加城市【'. $cityName. '】');
            }

            // 根据辖区名字找到对应区域
            $regionName = $shop['region'];
            $region = City::where('city_id', $city->city_id)->where('name', 'like', $regionName."%")->where('region_id', '<>', 0)->first();
            if (!$region) {
                $line = $key + 1;
                return self::fail(201, "第{$line}条数据【{$regionName}】不存在，请检查");
            }
            unset($shop['province']);
            $shop['city']   = $city->city_id;
            $shop['region'] = $region->id;
            $shop['type']   = $city->type;

            // 对门店进行重复检查
            $oldShop = Shop::where(['city' => $city->city_id, 'region' => $region->id, 'name' => $shop['name']])->first();
            if (!$oldShop) {
                Shop::create($shop);
            } else {
                $oldShop->update($shop);
            }
        }
        return self::success();
    }
}
